<template>
	<view class="content">
		<health-title @timeBack="timeBack" :borderBottom="false" height="100" Title="睡眠" :showWeek="false"></health-title>
		<view class="">
			<view class="box box2" v-if="dateType == '日'">
				<view class="title _df _ac">
					<image src="@/static/img/index/qxIcon3.png" mode=""></image>
					睡眠分布
				</view>
				<!-- <view class="txt">
					平均入睡时间:02:08 <br />
					平均起床时间 06:43
				</view>
				<view class="info">
					比上周平均降低4分钟
				</view> -->
				<view class="chart2">
					<l-echart ref="chartRef2"></l-echart>
					
				</view>
				<view class="legend">
					<view class="item _df _jb _ac">
						<view class="text">
							深睡
						</view>
						<view class="num">
							{{deepSleep}}
						</view>
					</view>
					<view class="item _df _jb _ac">
						<view class="text txt2">
							浅睡
						</view>
						<view class="num">
							{{lightSleep}}
						</view>
					</view>
					<view class="item _df _jb _ac">
						<view class="text txt3">
							清醒
						</view>
						<view class="num">
							{{awakeSleep}}
						</view>
					</view>
				</view>
			</view>
			<view class="box chart-box">
				<view class="title _df _ac">
					<image src="@/static/img/index/sleepIcon1.png" mode=""></image>
					睡眠时长
				</view>
				<view class="num-box _df _ac">
					{{dateType!='日'?'平均':''}}<view class="num">{{sleepHour}}</view> <span style="margin-top: 10rpx;">小时</span> <view class="num">{{sleepMinutes}}</view>{{sleepMinutes!=0?'分钟':''}}
				</view>
				<view class="chart-box-info">
					{{contrast}}
				</view>
				<view ref="chart" id="chart" class="chart" style="margin-top: -10rpx;padding-bottom: 50rpx;box-sizing: border-box;">
					<l-echart ref="chartRef"></l-echart>
				</view>
				
			</view>
			<view class="box3 _df _jb _ac" @click="toView">
				<view class="">
					了解睡眠
				</view>
				<u-icon name="arrow-right" color="#888" size="28"></u-icon>
			</view>
		</view>
		<!-- <send-order ref="blue" @blueBack="blueBack"></send-order> -->
	</view>
</template>

<script>
	import * as echarts from 'echarts';
	import moment from "moment";
	let timer;
	export default {
		data() {
			return {
				myChart:null,
				chartInstance: null,
				option: {},
				option2: {},
				page:{
					begin: "",
					end: "",
					type:1
				},
				xData:[],
				yData:[],
				yData2:[],
				format:'HH:mm',
				dateType:'日',
				infoData:{},
				sum:0,
				min:'',
				max:'',
				glTitle:'今日概览',
				seriesType:'line',
				deepSleep:'',
				lightSleep:'',
				awakeSleep:'',
				sleepHour:'',
				sleepMinutes:'',
				contrast:'',
				deviceId:'',
				notifyUuid:'',
				serviceId:'',
				writeId:'',
				dataObj:{},
				orderT:'0x74',
				// orderT:'0x63',
				orderDataList:[
					{
						id:0,
						name:'错误码',
						len:1,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:1,
						name:'采样间隔',
						len:1,
						value:'',
						data:'',
						dataLen:0
					},
					{
						id:2,
						name:'年月日',
						len:3,
						value:'',
						data:'',
						dataLen:0
					},{
						id:3,
						name:'当前数据总长度',
						len:2,
						value:'',
						data:'',
						dataLen:0
					},
				],
				datas:[],
				data2:[]
			}	
		},
		
		created() {
			
			
		},
		mounted() {
			
		},
		onReady() {
			
		},
		onLoad() {
			// this.$nextTick(()=>{
			// 	this.initChart2();
			// })
			
		},
		onShow() {
			// this.getData()
		},
		
		methods: {
			blueBack(e,ids){
				let that = this
				if(ids){
					this.deviceId = ids.deviceId
					this.notifyUuid = ids.notifyUuid
					this.serviceId = ids.serviceId
					this.writeId = ids.writeId
				}
				// let strVal = uni.getStorageSync('isJoin');
				if(e){
					// this.startNotice()
					// setTimeout(()=>{
					// 	// that.orderT = '0x0d'
					// 	this.orderT = '0x74'
					// 	let order = 'da740300' + uni.$_getTimeOrder(this.page.begin)
					// 	this.writeFn(order)
					// },1000)
				}else{
					// uni.showToast({
					// 	title:'请连接手表',
					// 	icon:'none'
					// })
					this.$refs.blue.getWatch()
				}
			},
			//订阅蓝牙消息返回
			startNotice() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: this.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						//接收蓝牙返回消息
						// that.listenValueChange()
						console.log('接收蓝牙返回消息订阅成功')
						setTimeout(()=>{
							// that.orderT = '0x0d'
							that.orderT = '0x74'
							let order = 'da740300' + uni.$_getTimeOrder(that.page.begin)
							that.writeFn(order)
						},1000)
						// timer = setInterval(()=>{
							
						// },1000)
						
					},
					fail(err) {
						console.log(err)
						uni.hideLoading()
					}
				})
			},
			writeFn(orderVal) {
				var that = this
				let crc = uni.$_getCrc_16_ibm(orderVal)
				let val = orderVal + crc
				console.log(val, '发送的指令')
				let buff = uni.$_hexStringToArrayBuffer(val)
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.writeId, //第二步写入的特征值
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log("写入成功", res)
						uni.onBLECharacteristicValueChange(result => {
							// console.log("监听低功耗蓝牙设备的特征值变化", result);
							if (result.value) {
								if(that.orderT == '0x74'){
									let resHex = uni.$_ab2hex(result.value)
									let str = ''
									str = str + resHex
									console.log('设备返回原始数据', str)
									that.dataObj = uni.$_parse_blue_response(str, 2)
									
									// clearInterval(timer)
									if(that.dataObj.Head == 'da' || that.dataObj.Cmd == "74") {
										// that.writeFn('da0d0000')
										that.dataToArr(that.dataObj.Data,that.orderDataList)
									}
								}
								
							}
						})
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading()
						that.$refs.blue.getWatch()
						// uni.showToast({
						// 	title:'请连接手表！',
						// 	icon:'none'
						// })
					},
					// complete: function() {
					// 	console.log("调用结束");
					// }
				})
			},
			dataToArr(dataList,orderDataList){
				console.log(dataList)
				let arr = []
				let arr2 = []
				let arr3 = []
				let arr4 = []
				dataList.forEach((item,index) =>{
					let time = 60 * (index + 1)
					let hours = Math.floor(time / (60 * 60));
					  let divisor_for_minutes = time % (60 * 60);
					  let minutes = Math.floor(divisor_for_minutes / 60);
					  let divisor_for_seconds = divisor_for_minutes % 60;
					  let seconds = Math.floor(divisor_for_seconds);
					  if(hours<10){
					  	hours = '0'+ hours
					  }
					  if(minutes<10){
					  	minutes = '0'+ minutes
					  }
					  if(seconds<10){
					  	seconds = '0'+ seconds
					  }
					
					
					let timeVal = this.page.begin + ' ' + hours+':' + minutes+':' + seconds
					if(item != '00'){
						let val = uni.$_hex2int(item)
						let obj = {
							time:timeVal,
							value:val
						}
						arr.push(obj)
					}
					 if(item == "02"){
						// let val2 = uni.$_hex2int(item)
						
						let obj2 = {
							time:timeVal,
							value:item
						}
						arr2.push(obj2)
						
						this.data2 = arr2.concat(arr2)
						console.log('浅睡',this.data2.length)
					}
					
					
				})
				this.datas = this.datas.concat(arr)
				
				// console.log('睡眠数据',this.datas)
				// console.log('浅睡',this.data2.length)
			},
			getData(){
				let that = this
				uni.$_post({
					url: "getSleep",
					that: that,
					params: that.page,
					success(res) {
						console.log(res)
						let chartData = res.data;
						that.infoData = res.data;
						// that.sum = that.infoData.maxCount + that.infoData.minCount
						if(res.code == 0){
							let value = chartData.dataList.averageTime.split(":")
							that.sleepHour = value[0]
							that.sleepMinutes = value[1]
							that.contrast = chartData.dataList.contrast
							that.deepSleep = that.convertMinutesToHours(chartData.dataList.deepSleepPercentage)
							that.lightSleep = that.convertMinutesToHours(chartData.dataList.lightSleepPercentage)
							that.awakeSleep = that.convertMinutesToHours(chartData.dataList.awakeSleepPercentage)
							
							that.initChart(chartData);
							
						}else{
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon:'error'
							});
						}
					},
					fail(err) {
						uni.showToast({
							title: err.msg,
							duration: 1000,
							icon:'error'
						});	
					},
				});
			},
			toView(){
				uni.navigateTo({
					url:'/pages/comA/details?title=了解睡眠' + '&type=3694'
				})
			},
			timeBack(e) {
				
				if(e.dateTxt == '月'){
					this.format = 'MM-DD'
					this.page.type = 3
				}else if(e.dateTxt == '周'){
					this.format = 'MM-DD'
					this.page.type = 2
				}else if(e.dateTxt == '日'){
					this.format = 'HH:mm'
					this.page.type = 1
					console.log(uni.$_getTimeOrder(e.sTime))
				}
				this.dateType = e.dateTxt
				this.page.begin = e.sTime
				this.page.end = e.eTime
				this.getData()
			},
			convertMinutesToHours(minutes) {
			  var hours = Math.floor(minutes / 60); // 计算小时数，使用Math.floor取整
			  var remainingMinutes = minutes % 60; // 计算剩余的分钟数
			  return hours + "小时" + remainingMinutes + "分钟";
			},
			initChart(chartData) {
				if(!chartData) return
				let that = this
				let xData = chartData.dateList
				let yData1 = chartData.dataList.awakeSleep
				let yData2 = chartData.dataList.deepSleep
				let yData3 = chartData.dataList.lightSleep
				
				this.option = {
						legend: {
							show: true ,
							top:20,
							data: ['深睡', '浅睡','清醒']
						},
						tooltip: {
						    trigger: 'axis',
						    axisPointer: {
						      type: 'shadow'
						    },
							confine: true,
							formatter: function (params) {
								// params 是一个数组，数组中包含每个系列的数据信息
								let result = '';//收缩压信息窗结果
								let arr = []//总数组
								arr = params
								console.log(arr,999)
								let name = ''//时间
								arr.forEach(function (item) {
									// item 是每一个系列的数据
									// seriesName = item.seriesName; // 系列名称
									// marker = item.marker; // 系列名称
									 // 数据值
									 let value = ''
									 name = item.name
									 value = that.convertMinutesToHours(item.value)
									result += `\n${item.marker}${item.seriesName}: ${value} `;
								});

								// if(arr.length<=2){
								// 	result = `${marker}${seriesName}: ${min}`;
								// }else{
								// 	result = `${marker}${seriesName}: ${min}-${max}`;
								// }
								return name + result;
								
								
							}
						  },
					  xAxis: {
						  splitLine: {
							show: false   //隐藏x轴那条线
						  },
						  axisTick: {
							show: false   //隐藏x轴的刻度
						  },
						  axisLine: {
							show: false   
						  },
						  axisLabel: {
						    	showMaxLabel: true,
						    	boundaryGap: false,
								interval: 'auto',
						    	textStyle: {
						    	    color: "#999",
						    	    fontSize: '10',
						    	    lineHeight: 30,
						    	},
								formatter: function(value, index) {
									return moment(value).format(that.format);
								}
						  },
						type: 'category',
						data: xData,
					  },
					  color: ['#00c1ff','#0085ff','#2028bd','#B2E8FF'],
					  grid: {
					  	left: '1%',
					  	right: '4%',
					  	bottom: '3%',
					  	containLabel: true
					  },
					  yAxis: {
						type: 'value',
						position: 'left',
						axisLabel: {
							textStyle: {
								color: "#999",
								fontSize: '12',
							},
							// formatter: `{value}`
						},
						axisLine: {
							show: false,
							lineStyle:{
								color:"#999"
							}
						},
					  },
					  series:  [
						  {
						    data: yData1,
						    type: 'bar',
						    // barWidth: 25,
						    barGap: '50%',
						    stack: 'a',
						    name: '清醒'
						  },
						  {
						    data: yData3,
						    type: 'bar',
						    stack: 'a',
						    // barWidth: 25,
						    barGap: '50%',
						    name: '浅睡'
						  },
						{
						  data: yData2,
						  type: 'bar',
						  // barWidth: 25,
						  stack: 'a',
						  barGap: '50%',
						  name: '深睡',
						  itemStyle: {
							opacity:0.9,
							borderRadius: [6, 6, 0, 0]
						  },
						},
						
						
					  ]
					}
					
				//睡眠分布
				this.option2 = {
					tooltip: {
						show:false,
						trigger: 'item',
						valueFormatter: function(value) {
						  return (value / chartData.dataList.countSleep * 100).toFixed(2) + ' %'
						}
					},
					grid: {
						left: '4%',
						// right: 'auto',
						bottom: '3%',
						containLabel: false,
						
					},
					
					color: ['#2028bd','#0085ff','#00c1ff'],
					series: [
						{
							name: '',
							type: 'pie',
							width:'70%',
							center: ['40%', '60%'],
							radius: ['30%', '70%'],
							avoidLabelOverlap: false,
							label: {
								show: false,
							},
							emphasis: {
								label: {
									show: false,
									fontSize: '40',
									fontWeight: 'bold'
								}
							},
							labelLine: {
								show: false
							},
							bottom:20,
							data: [
								{value: chartData.dataList.deepSleepPercentage, name: '深睡'},
								{value: chartData.dataList.lightSleepPercentage, name: '浅睡'},
								{value: chartData.dataList.awakeSleepPercentage, name: '清醒'},
							]
						}
					]
				}
				this.$refs.chartRef.init(this.$echarts, chart=> {
					chart.setOption(this.option);
				});
				
				this.$refs.chartRef2.init(this.$echarts, chart=> {
					chart.setOption(this.option2);
				});
				setTimeout(()=>{
					this.$refs.chartRef.setOption(this.option)
					this.$refs.chartRef2.setOption(this.option2)
				},200)
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	/deep/.lime-echart__canvas{
		height: 100% !important;
	}
	.content {
		padding: 0 30rpx 100rpx;
		.box{
			background: #ffffff;
			border-radius: 24rpx;
			box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.10); 
			padding: 40rpx 30rpx 10rpx;
			margin-bottom: 30rpx;
			.title{
				padding-bottom: 40rpx;
				// border-bottom: 1rpx solid #eee;
				color: #171717;
				font-family: $uni-font-family-Bold;
				font-size: 28rpx;
				image{
					width: 60rpx;
					height: 60rpx;
					margin-right: 20rpx;
				}
			}
			.info {
				height: 48rpx;
				line-height: 48rpx;
				padding-left: 30rpx;
				background: #f8f5ff;
				border-radius: 6rpx;
				font-size: 22rpx;
				font-family: $uni-font-family-Medium;
				color: #795DFF;
			}
		}
		.chart-box-info{
			height: 48rpx;
			line-height: 48rpx;
			padding-left: 30rpx;
			background: #f8f5ff;
			border-radius: 6rpx;
			font-size: 22rpx;
			font-family: $uni-font-family-Medium;
			color: #795DFF;
		}
		.box2{
			background: #ffffff;
			border-radius: 24rpx;
			box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.10); 
			padding: 40rpx 30rpx 50rpx;
			margin-bottom: 30rpx;
			position: relative;
			.chart2{
				height: 400rpx;
				margin-top: -30rpx;
				#lime-echart61{
					height: 400rpx !important;
				}
			}
			
			.legend{
				position: absolute;
				top: 35%;
				right: 30rpx;
				z-index: 1;
				.item{
					margin: 40rpx 0;
					height: 40rpx;
					.text{
						padding-left: 20rpx;
						font-size: 28rpx;
						color: #666;
						position: relative;
						margin-right: 30rpx;
						&::before{
							display: block;
							content: '';
							width: 14rpx;
							height: 24rpx;
							background-color: #2028bd;
							position: absolute;
							left: 0;
							top: 50%;
							margin-top: -12rpx;
						}
					}
					.txt2{
						
						&::before{
							background-color: #0085ff;
							
						}
					}
					.txt3{
						
						&::before{
							background-color: #00c1ff;
							
						}
					}
					.txt4{
						
						&::before{
							background-color: #B2E8FF;
							
						}
					}
					.num{
						font-size: 28rpx;
						color: #666;
						font-family: $uni-font-family-Bold;
					}
				}
			}
			.title{
				padding-bottom: 20rpx;
				// border-bottom: 1rpx solid #eee;
				color: #171717;
				font-family: $uni-font-family-Bold;
				font-size: 28rpx;
				image{
					width: 60rpx;
					height: 60rpx;
					margin-right: 20rpx;
				}
			}
			.txt{
				line-height: 54rpx;
				color: #171717;
				font-family: $uni-font-family-Bold;
				font-size: 27rpx;
				margin-bottom: 15rpx;
			}
			.list{
				padding-top: 40rpx;
				display: flex;
				flex-wrap: wrap;
				.item{
					width: 50%;
					padding-left: 50rpx;
					padding-top: 10rpx;
					box-sizing: border-box;
					margin-bottom: 50rpx;
					position: relative;
					&::before{
						display: block;
						content: '';
						width: 1rpx;
						height: 70rpx;
						background-color: #e2e2e2;
						position: absolute;
						top: 50%;
						right: 0;
						margin-top: -35rpx;
					}
					.num-box{
						height: 58rpx;
						line-height: 58rpx;
						font-family: $uni-font-family-Bold;
						font-size: 50rpx;
						color: #171717;
						margin-right: 4rpx;
						.dw{
							font-size: 24rpx;
							line-height: 70rpx;
						}
					}
					.info{
						height: 48rpx;
						line-height: 48rpx;
						font-family: $uni-font-family-Medium;
						font-size: 24rpx;
						color: #222;
					}
				}
				.item:nth-child(2),
				.item:nth-child(4){
					&::before{
						display: none;
					}
				}
			}
		}
		.box3{
			background: #ffffff;
			border-radius: 24rpx;
			box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0,0,0,0.10); 
			height: 130rpx;
			padding: 0 30rpx;
			color: #222;
			font-family: $uni-font-family-Bold;
			font-size: 28rpx;
		}
	}
</style>